<?php

namespace app\api\controller;
use data\Json;
use think\Request;
use think\Cache;
use think\Log;
use think\Db;
use JPush\Client as JPush;
use controller\Easemob;
use app\common\model\Travel as TravelModel;
use app\common\model\TravelMember;
use app\common\model\Activity;
/**
 * 用户api接口
 */
class Chat extends Base
{
    protected $user_model = null;
    protected $token = null;
    protected $user = null;

     /**
     * 插入聊天记录
     */
    public function chat_history()
    {
        $list = getChatHistory();
        foreach($list as $value)
        {
           $chat = Db::name('chat')->where('msg_id',$value['msg_id'])->find();
           // 根据 msg_id判断此聊天记录是否存在，如果存在不插入，存在则插入数据库
           if(!$chat)
           {
              $value['payload'] = json_encode($value['payload'],JSON_UNESCAPED_UNICODE);
              Db::name('chat')->insert($value);
              Log::info('聊天记录', $value['msg_id'].'插入成功');
           }
        }
    }

    public function getChatRecord()
    {
         $h = new Easemob();
         $result = $h->getChatRecord('2018011517');
        // var_dump($result['data'][0]['url']);exit;
         $return = postCurl($result['data'][0]['url'],'get');
         return Json::json_send(0,'',$return);
    }

     /**
     * 会员获取聊天记录
     */
    public function hxchat(Request $request)
    {
        if(!$request->header('token') || $this->LoginAuth($request->header('token')) == false)
        {
            return $this->sendError(400);
        }

        $memberinfo = Db::name($this->member_model)->field('hx_username,hx_password,head_img,username')->where('id', $this->client)->find();

        $chats = Db::name('chat')
                  ->where('from', $memberinfo['hx_username'])
                  ->whereOr('to', $memberinfo['hx_username'])
                  ->order('timestamp asc')
                  ->select();

        if($chats)
        {
            foreach ($chats as $ck => $cv) 
            {
                $chats[$ck]['payload'] = json_decode($cv['payload'],true);
            }
        } 

        return $this->sendSuccess($chats);
    }
}
